package org.kineticsproject.devices.parsers;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

import data.DataFactory;
import data.DataLog;
import data.Exercise;
import data.HeartRateSample;
import data.PositionSample;

public class PolarParser extends Parser {
	
	private FileInputStream fis;
	private DataInputStream dis;
    private File            f;
   // private ErrorHandler	eh;
    private StringTokenizer strtok;
    
	@Override
	public boolean process(Exercise exercise, String filename, String newdate,
			long timeOffset) {
		  int 			i 				= 0;
		  boolean 		result 			= true;    
		 // FileErrorInfo fei 			= new FileErrorInfo();
		 // ErrorInfo     ei              = new ErrorInfo();
		  DataLog  		posDataLog 		= DataFactory.eINSTANCE.createDataLog();
		  DataLog       hrDataLog  		= DataFactory.eINSTANCE.createDataLog();

		 // dataLogSet.add(posDataLog);
		  //dataLogSet.add(hrDataLog);
		  exercise.getDatalogs().add(hrDataLog);
		  
//		  ErrorInfo     ei  = new ErrorInfo();
		 
		  /* Open File */
			 try 
			 {
				// eh  = new ErrorHandler();
				 f 	 = new File(filename);
				 fis = new FileInputStream(f);
				 dis = new DataInputStream(fis);
			 }
			 catch(IOException ex)
			 {
				// eh.process(ErrorHandler.FILENOTFOUND_EXCEPTION,fei); 
			 }
			 
		 try {
		       while (i < 1) // skip header
		       {
		    	   //System.out.println(dis.readLine());
		    	   dis.readLine();
		    	   ++i;
		       }
			 }
		 catch(IOException ex)
		 {
			// eh.process(ErrorHandler.FILEREAD_EXCEPTION,fei);
		 }
		 
		i=0;
		 try {
	       while ((dis.available() != 0) )
	       {
	    	
	    	   {   
	    	   ++i;
	    	   String str;
	    	   String sAltitude;
	    	   String sHeartRate;
	    	   String sTimeAMPM;
	    	   String sTime; 
	    	   String sTimeHour;
	    	   String sTimeMinutes;
	    	   String sTimeSeconds;
	    	   str = dis.readLine();

	    	  
	    	   strtok = new StringTokenizer(str);
	    	//   while (strtok.hasMoreTokens())
	    	   {
	    		   
	    		   try
	    		   {
	    			   
	    		  
	    		   sTime        	=   strtok.nextToken(); // Time
	    		 //  if (timeOffset == 0)
	    		   sTimeAMPM        =   strtok.nextToken(); // AM/PM
	    		//   else sTimeAMPM = "";
	    		   sHeartRate       =   strtok.nextToken(); // Heart Rate
	    		   sAltitude 		=   strtok.nextToken(); // Altitude
	    		   
	    		   PositionSample       psample 	= DataFactory.eINSTANCE.createPositionSample();
	    		   HeartRateSample      hrsample 	= DataFactory.eINSTANCE.createHeartRateSample();
  		   
	    		   StringTokenizer strtokTime = new StringTokenizer(sTime,":");
	    		   
	    
	    		   if (sTimeAMPM.compareTo("PM") == 0)  // convert to 24hr clock
	    		   sTimeHour 	= String.valueOf((Integer.valueOf(strtokTime.nextToken()).intValue()%12)+12);
	    		   else
	    			   sTimeHour 	= (String.valueOf(Integer.valueOf(strtokTime.nextToken()).intValue()%12));
	    		   
	    		   sTimeMinutes	= strtokTime.nextToken();
	    		   sTimeSeconds  = strtokTime.nextToken();
	    		   
	    		   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	    	//		   System.out.println(/*2006-04-11*/newdate+" "+sTimeHour+":"+sTimeMinutes+":"+sTimeSeconds);

	    		   try
	    		   {
	    		   Date sampleDate = simpleDateFormat.parse(newdate+" "+sTimeHour+":"+sTimeMinutes+":"+sTimeSeconds);
	    		
	    		   sampleDate.setTime(sampleDate.getTime()+timeOffset); //ofset time
	    		  
	    	//	   Date sampleDate = simpleDateFormat.parse("2006-06-12 05:22:28");
	    		//   System.out.println("Parsed: "+sampleDate.toString());
	    		   
	    		  // Timestamp hrtimestamp = new Timestamp(sampleDate.getTime());
	    		  // hrsample.setTimestamp(hrtimestamp);
	    		   hrsample.setTimestamp(new Timestamp(sampleDate.getTime()));	    		   
	    		   psample.setTimestamp(new Timestamp(sampleDate.getTime()));
	    		   
	    	//	   System.out.println("Mili: "+psample.getTimestamp().toString());
	    		   }
	    		   catch (ParseException e)
	    		   {
	    			  // eh.process(ErrorHandler.DATE_PARSE_EXCEPTION,ei);
	    		   }
	    				   
	    		   hrsample.setHeartRate(Integer.valueOf(sHeartRate).intValue());

	    		 //  hrsample.setDataLog(hrDataLog);
	    		  // hrsample.setDataLogId(hrDataLog.getDataLogId()); 
	    		  // hrDataLog.add(hrsample);
	    		   hrDataLog.getDataSamples().add(hrsample);
	    		   
	    		   psample.setAltitude(Integer.parseInt(sAltitude));


	    		  // psample.setDataLog(posDataLog);
	    		   //psample.setDataLogId(posDataLog.getDataLogId());
	    		  // posDataLog.add(psample);
	    		   posDataLog.getDataSamples().add(psample);
	    		   
	    		   }
	    		   catch (java.util.NoSuchElementException e)
	    		   {
	    			   //fei.setValid(true);
	    			  // fei.setLine(i);
	    			  // fei.setFilename(filename);
	    			  // eh.process(ErrorHandler.NOSUCHELEMENT_EXCEPTION,fei);   
	    		   }
	    	   }
	    	   }
	       }
		 }
		 catch(IOException ex)
		 {
			// eh.process(ErrorHandler.FILEREAD_EXCEPTION,fei);
		 }
		 System.out.println(i+" HR samples added.");
		 close();
			  
		 return(result);
			  
	}
	
	  private void close()
	  {
		//  FileErrorInfo fei = new FileErrorInfo();
		try
		{
			  fis.close();
		}
		catch(IOException ex)
		{
			//eh.process(ErrorHandler.FILENOTCLOSED_EXCEPTION,fei);
		}  
	  }
	  
	  private int StringtoInt(String input)
	  {
		//  ErrorInfo ei = new ErrorInfo();
		  int result = 0;
		  try
		  {
		  result = Integer.valueOf(input).intValue();
		  }
		  catch(java.lang.NumberFormatException e)
		  {
			  //eh.process(ErrorHandler.NUMBERFORMAT_EXCEPTION,ei);
		  }
		  return(result);
	  }


}
